@Service
public class EnrollmentService {
    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private EnrollmentMapper enrollmentMapper;

    // 选课操作（事务管理）
    @Transactional(rollbackFor = Exception.class)
    public void enrollCourse(Integer studentId, Integer courseId) {
        // 1. 检查课程容量并减少容量
        int updated = courseMapper.decreaseCourseCapacity(courseId);
        if (updated == 0) {
            throw new RuntimeException("课程已满或不存在");
        }

        // 2. 插入选课记录
        Enrollment enrollment = new Enrollment();
        enrollment.setStudentId(studentId);
        enrollment.setCourseId(courseId);
        enrollmentMapper.insertEnrollment(enrollment);
    }
}